<!--
 * @Author: Liz.Zheng
 * @Date: 2021-11-23 11:04:47
 * @LastEditTime: 2022-12-06 17:12:53
 * @LastEditors: 郑亚莉 zhengyali@shequ.life
 * @Description: 添加集合
 * @Motto: Write the code. Change the world.
-->

<template>
  <a-drawer
    :title="title"
    placement="right"
    :closable="true"
    :maskClosable="true"
    :visible="visible"
    :width="600"
    @close="handleClose"
    :body-style="{
      paddingBottom: '80px',
    }"
  >
    <a-form layout="vertical">
      <a-form-item label="集合名称" v-bind="validateInfos.collection_name">
        <a-input
          placeholder="请输入..."
          v-model:value="modelRef.collection_name"
        />
      </a-form-item>
      <a-form-item label="选择楼宇">
        <ul class="building-list">
          <li
            class="building-item"
            v-for="item of buildingList"
            :key="item.id"
            :class="item.checked ? 'active' : ''"
            @click="handleBuildChecked(item)"
          >
            {{ item.build_name || "--" }}
            <CheckOutlined v-if="item.checked" />
          </li>
        </ul>
      </a-form-item>
    </a-form>
    <div class="drawer-footer">
      <a-button class="mr-10" @click.prevent="handleClose">关闭</a-button>
      <a-button type="primary" @click.prevent="handleSuccess">保存</a-button>
    </div>
  </a-drawer>
</template>

<script>
import { computed, defineComponent, ref, watch, reactive, toRaw } from "vue";
import { CheckOutlined } from "@ant-design/icons-vue";
import request from "../../../../common/utils/request";
import { Form, message } from "ant-design-vue";
import store from "../../../../store";
const useForm = Form.useForm;

export default defineComponent({
  name: "BucketsAdd",
  components: { CheckOutlined },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    id: {
      type: [String, Number],
      default: 0,
    },
    villageType: {
      type: String,
      default: "",
    },
  },
  setup(props, context) {
    const title = computed(() => (props.id ? "编辑集合" : "添加集合"));
    const modelRef = reactive({
      collection_name: "",
    });
    const rulesRef = reactive({
      collection_name: [{ required: true, message: "请填写集合名称" }],
    });
    const { resetFields, validate, validateInfos } = useForm(
      modelRef,
      rulesRef
    );

    const buildingList = computed(() => store.getters.allBuildings);
    let checkedBuildings = [];
    const handleBuildChecked = (build) => {
      build.checked = !build.checked;
      const index = checkedBuildings.findIndex((id) => id == build.id);
      if (!build.checked && index > -1) {
        checkedBuildings.splice(index, 1);
      } else if (build.checked && index == -1) {
        checkedBuildings.push(build.id);
      }
    };

    const handleClose = () => {
      context.emit("cancel");
    };
    const handleSuccess = () => {
      validate().then(() => {
        if (!checkedBuildings.length) {
          message.warning("请选择楼宇~");
          return;
        }
        let params = {
          ...toRaw(modelRef),
          village_type: props.villageType,
          needMsg: true,
        };
        params.collection_build = JSON.stringify(checkedBuildings);
        const success = (res) => {
          message.success(res.msg || "保存成功");
          context.emit("success");
        };
        if (props.id) {
          params.id = props.id;
          request
            .put("/org", "/build/collection", params)
            .then((res) => success(res));
        } else {
          request
            .post("/org", "/build/collection", params)
            .then((res) => success(res));
        }
      });
    };

    const getDetail = () => {
      request
        .get("/org", "/build/collectionDetail", {
          id: props.id,
        })
        .then((res) => {
          modelRef.collection_name = res.data.collection_name;
          checkedBuildings = res.data.collection_build;
          buildingList.value.forEach((build) => {
            build.checked = checkedBuildings.includes(build.id);
          });
        });
    };
    const init = () => {
      if (props.id) {
        getDetail();
      }
    };

    const resetData = () => {
      resetFields();
      checkedBuildings = [];
    };

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          init();
        } else {
          resetData();
        }
      }
    );

    return {
      title,
      modelRef,
      validateInfos,
      buildingList,
      handleClose,
      handleSuccess,
      handleBuildChecked,
    };
  },
});
</script>

<style lang="less" scoped>
.building-list {
  .building-item {
    width: 100%;
    background: #f1f1f1;
    height: 30px;
    display: flex;
    align-items: center;
    margin: 10px 0;
    padding: 10px;
    cursor: pointer;
    justify-content: space-between;
  }
  .active {
    background: @primary-color-bg;
    color: @primary-color;
  }
}
</style>
